package app

import (
	"context"

	"charging_pile/common/ctxdata"
	"charging_pile/common/xerr"
	"charging_pile/models"
	"charging_pile/user/internal/svc"
	"charging_pile/user/internal/types"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/stores/sqlx"

	"github.com/zeromicro/go-zero/core/logx"
)

type RechargeMoneyLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRechargeMoneyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RechargeMoneyLogic {
	return &RechargeMoneyLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RechargeMoneyLogic) RechargeMoney(req *types.Money) (resp *types.Wallet, err error) {
	uid := ctxdata.GetUidFromCtx(l.ctx)
	var wallet *models.Wallet

	err = l.svcCtx.Models.Wallet.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
		wallet, err = l.svcCtx.Models.Wallet.FindOneByUserId(l.ctx, uid)

		if err != nil && err != models.ErrNotFound {
			return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查找钱包数据错误")
		}

		if wallet != nil {
			wallet.Cash += int64(req.Money)
			err = l.svcCtx.Models.Wallet.UpdateWithVersion(l.ctx, session, wallet)
			if err != nil {
				return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "更新钱包失败")
			}
		} else {
			wallet = &models.Wallet{
				UserId: uid,
				Cash:   int64(req.Money),
				Gift:   0,
			}
			r, err := l.svcCtx.Models.Wallet.Insert(l.ctx, session, wallet)
			if err != nil {
				return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "创建钱包失败")
			}
			wallet.Id, _ = r.LastInsertId()
		}
		return nil
	})

	return &types.Wallet{
		Cash: int(wallet.Cash),
		Card: 0,
		Gift: int(wallet.Gift),
	}, nil
}
